package com.uplift.common.base;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Configuration
public class WebMvcConfigurer implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer {
    public WebMvcConfigurer() {
    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        exceptionResolvers.add(new HandlerExceptionResolver() {
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
                ModelAndView mv = new ModelAndView();
                JSONObject out = new JSONObject();
                if (e instanceof BusinessException) {
                    out.put("code", ((BusinessException)e).getCode());
                    out.put("data", ((BusinessException)e).getData());
                    response.setStatus(((BusinessException)e).getCode());
                } else {
                    out.put("code", 500);
                    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                }

                out.put("msg", e.getMessage());

                try {
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.setHeader("Cache-Control", "no-cache, must-revalidate");
                    response.getWriter().write(out.toJSONString());
                } catch (IOException var8) {
                    var8.printStackTrace();
                }

                return mv;
            }
        });
    }
}
